<template>
  <div class="admin-violations-container">
    <a-card title="当天限流违规统计" style="margin-bottom: 16px">
      <p>仅管理员可见。展示 Redisson 中记录的当天各限流 Key 的违规次数。</p>
    </a-card>

    <a-card>
      <a-alert v-if="!isAdmin" type="error" message="当前用户非管理员，无法查看此页面" show-icon style="margin-bottom: 16px" />
      <a-spin :spinning="loading">
        <a-table
          v-if="isAdmin"
          :data-source="tableData"
          :columns="columns"
          :pagination="false"
          row-key="key"
        />
      </a-spin>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { getTodayRateLimitViolations } from '@/api/monitor'

const loading = ref(false)
const violations = ref<Record<string, number>>({})

const userInfoStr = localStorage.getItem('userInfo')
const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null
const isAdmin = computed(() => userInfo?.userRole === 'admin')

const columns = [
  { title: '限流Key', dataIndex: 'key', key: 'key' },
  { title: '违规次数', dataIndex: 'count', key: 'count' },
]

const tableData = computed(() => {
  return Object.entries(violations.value).map(([key, count]) => ({ key, count }))
})

const fetchViolations = async () => {
  if (!isAdmin.value) {
    return
  }
  try {
    loading.value = true
    const res = await getTodayRateLimitViolations()
    if (res.code === 0) {
      violations.value = res.data || {}
    } else {
      message.error(res.message || '获取违规统计失败')
    }
  } catch (err: any) {
    console.error('获取违规统计错误:', err)
    message.error(err?.message || '获取违规统计失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchViolations()
})
</script>

<style scoped>
.admin-violations-container {
  max-width: 960px;
  margin: 0 auto;
}
</style>